<template>
  <div class="order-basic-info">
    <h3>基础信息</h3>
    <el-form :model="form" label-width="100px">
      <!-- 基本信息 -->
      <el-row>
        <el-col :span="8">
          <el-form-item label="订单编号" prop="orderBasic.orderId">
            <el-input v-model="form.orderBasic.orderId" placeholder="请输入内容" disabled />
          </el-form-item>
          <el-form-item label="始发地" prop="orderBasic.origin">
            <el-select v-model="form.orderBasic.origin" placeholder="请选择">
              <el-option label="北京" value="北京"></el-option>
              <el-option label="上海" value="上海"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运输类型" prop="orderBasic.transportType">
            <el-select v-model="form.orderBasic.transportType" placeholder="请选择">
              <el-option label="公路" value="公路"></el-option>
              <el-option label="铁路" value="铁路"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="订单来源" prop="orderBasic.orderSource">
            <el-select v-model="form.orderBasic.orderSource" placeholder="请选择">
              <el-option label="线上" value="线上"></el-option>
              <el-option label="线下" value="线下"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item  label="客户名称" prop="orderBasic.customerName">
            <el-select v-model="form.orderBasic.customerName" @change="handleCustomerChange" placeholder="请选择">
              <!--  <el-option label="客户A" value="客户A"></el-option>
              <el-option label="客户B" value="客户B"></el-option>-->
              <el-option
                v-for="item in customerInfo"
                :key="item.id"
                :label="item.customerName"
                :value="item.customerName"
                :data-code="item.customerNumber"
                :data-name="item.contactName"
                :data-phone="item.phoneNumber"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目的地" prop="orderBasic.destination">
            <el-select v-model="form.orderBasic.destination" placeholder="请选择">
              <el-option label="广州" value="广州"></el-option>
              <el-option label="深圳" value="深圳"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货物类型" prop="orderBasic.goodsType">
            <el-select v-model="form.orderBasic.goodsType" placeholder="请选择">
              <el-option label="电子产品" value="电子产品"></el-option>
              <el-option label="日用品" value="日用品"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下单时间" prop="orderBasic.orderTime">
            <el-date-picker
              v-model="form.orderBasic.orderTime"
              @change="handleOrderTimeChange"
              type="datetime"
              placeholder="请选择时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户编码" prop="orderBasic.customerCode">
            <el-input v-model="form.orderBasic.customerCode" placeholder="选择客户"
                      readonly />
          </el-form-item>
          <el-form-item label="合同" prop="orderBasic.contract">
            <el-select v-model="form.orderBasic.contract" placeholder="请选择">
              <el-option label="合同1" value="合同1"></el-option>
              <el-option label="合同2" value="合同2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 收发信息 -->
      <el-row>
        <el-col :span="12">
          <div class="send-section">
            <h4>发</h4>
            <el-form-item label="联系人" prop="orderBasic.senderContact">
              <el-input v-model="form.orderBasic.senderContact" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="联系电话" prop="orderBasic.senderPhone">
              <el-input v-model="form.orderBasic.senderPhone" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="详细地址" prop="orderBasic.senderAddress">
              <el-input v-model="form.orderBasic.senderAddress" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="计划发货时间" prop="orderBasic.planSendTime">
              <el-date-picker
                v-model="form.orderBasic.planSendTime"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="receive-section">
            <h4>收</h4>
            <el-form-item label="联系人" prop="orderBasic.receiverContact">
              <el-input v-model="form.orderBasic.receiverContact" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="联系电话" prop="orderBasic.receiverPhone">
              <el-input v-model="form.orderBasic.receiverPhone" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="详细地址" prop="orderBasic.receiverAddress">
              <el-input v-model="form.orderBasic.receiverAddress" placeholder="请输入内容" />
            </el-form-item>
            <el-form-item label="计划收货时间" prop="orderBasic.planReceiveTime">
              <el-date-picker
                v-model="form.orderBasic.planReceiveTime"
                type="datetime"
                placeholder="请选择时间"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <!-- 货物信息区域 -->
      <div class="goods-vehicle-cost">
        <el-card shadow="never" class="goods-info-card">
          <div slot="header" class="clearfix">
            <span>货物信息</span>
          </div>
          <el-button type="primary" size="small" @click="addGoods">+ 添加</el-button>
          <el-table
            :data="goodsList"
            border
            style="width: 100%; margin-top: 10px"
            :header-cell-style="{ background: '#f5f7fa' }"
          >
            <el-table-column prop="goodsId" label="序号" width="50"></el-table-column>
            <el-table-column prop="goodsName" label="货物名称"></el-table-column>
            <el-table-column prop="quantity" label="数量"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
            <el-table-column prop="volume" label="体积 (m³)"></el-table-column>
            <el-table-column prop="weight" label="重量 (kg)"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  style="color: #f56c6c"
                  @click="deleteGoods(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="goods-total">
            合计：总数量：{{ totalQuantity }} 总体积：{{ totalVolume }}m³ 总质量：{{ totalWeight }}kg
          </div>
        </el-card>

        <!-- 添加货物对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="goodsForm" :model="goodsInfo" label-width="100px">

            <el-form-item label="货物名称" prop="goodsName">
              <el-input v-model="goodsInfo.goodsName" placeholder="请输入货物名称" />
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="goodsInfo.quantity" placeholder="请输入货物数量" type="number" />
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-input v-model="goodsInfo.unit" placeholder="请输入单位" />
            </el-form-item>
            <el-form-item label="体积" prop="volume">
              <el-input-number v-model="goodsInfo.volume" controls-position="right" :min="0" placeholder="请输入体积" />
            </el-form-item>
            <el-form-item label="重量" prop="weight">
              <el-input v-model="goodsInfo.weight" placeholder="请输入重量" type="number" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancelDialog">取 消</el-button>
          </div>
        </el-dialog>
      </div>

      <!-- 需求车辆和费用信息区域 -->
      <div>
        <!-- 需求车辆区域 -->
        <el-card shadow="never" class="vehicle-info-card" style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>需求车辆</span>
          </div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车型">
                <el-select v-model="form.vehicleRequirement.vehicleType" placeholder="请选择">
                  <el-option label="厢式货车" value="厢式货车"></el-option>
                  <el-option label="冷藏车" value="冷藏车"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车长">
                <el-select v-model="form.vehicleRequirement.vehicleLength" placeholder="请选择">
                  <el-option label="4.2米" value="4.2m"></el-option>
                  <el-option label="6.8米" value="6.8m"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="用车数量">
                <el-input v-model="form.vehicleRequirement.vehicleCount" placeholder="请输入内容" type="number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 费用信息区域 -->
        <el-card shadow="never" class="cost-info-card" style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>费用信息</span>
          </div>
          <el-row>
            <el-col :span="8">
              <el-form-item label="计费方式" required>
                <el-select v-model="form.costInfo.billingMethod" placeholder="请选择">
                  <el-option label="按重量" value="按重量"></el-option>
                  <el-option label="按体积" value="按体积"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="包装费">
                <el-input v-model="form.costInfo.packagingFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
              <el-form-item label="燃油费">
                <el-input v-model="form.costInfo.fuelFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运输费">
                <el-input v-model="form.costInfo.transportFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
              <el-form-item label="装卸费">
                <el-input v-model="form.costInfo.loadingUnloadingFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
              <el-form-item label="服务费">
                <el-input v-model="form.costInfo.serviceFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保险费">
                <el-input v-model="form.costInfo.insuranceFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
              <el-form-item label="中转费">
                <el-input v-model="form.costInfo.transferFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
              <el-form-item label="其他费用">
                <el-input v-model="form.costInfo.otherFee" placeholder="请输入内容" type="number" @change="sumTotalFee"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="费用合计" required>
                <el-input v-model="form.costInfo.totalCost" placeholder="请输入内容" type="number"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <!-- 付款方式信息区域 -->
      <el-card shadow="never" class="cost-info-card" style="margin-top: 20px">
        <div class="payment-method">
          <h3>付款方式</h3>
          <el-row type="flex" justify="center">
            <el-col :span="8">
              <el-form-item label="现付" prop="cashPayment">
                <el-input v-model="form.paymentMethod.cashPayment" placeholder="请输入内容" @change="sumTotalMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="预付" prop="prePayment">
                <el-input v-model="form.paymentMethod.prePayment" placeholder="请输入内容" @change="sumTotalMoney"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="到付" prop="cashOnDelivery">
                <el-input v-model="form.paymentMethod.cashOnDelivery" placeholder="请输入内容" @change="sumTotalMoney"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="周期付" prop="periodicPayment">
                <el-input v-model="form.paymentMethod.periodicPayment" placeholder="请输入内容" @change="sumTotalMoney"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="付费合计" prop="totalPayment">
                <el-input v-model="form.paymentMethod.totalPayment" placeholder="请输入内容" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 订单备注区域 -->
      <el-card shadow="never" class="cost-info-card" style="margin-top: 20px">
        <div class="payment-method">
          <h3>订单备注</h3>
          <el-row type="flex" justify="center">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.orderRemark.remark" placeholder="请输入内容" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <div class="button-group">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {addOrder, getCustomerInfo, requestOrderId} from "@/api/tms/orders/order";

export default {
  name: "createOrder",
  data() {
    return {
      title: "",
      open: false,
      time: undefined,
      form: {
        // 基本信息
        orderBasic: {
          orderId: "",
          customerName: "",
          customerCode: "",
          origin: "",
          destination: "",
          contract: "",
          transportType: "",
          goodsType: "",
          orderSource: "",
          orderTime: "",
          senderContact: "",
          senderPhone: "",
          senderAddress: "",
          planSendTime: "",
          receiverContact: "",
          receiverPhone: "",
          receiverAddress: "",
          planReceiveTime: "",
          totalQuantity: "",   // 总数量
          totalVolume: "",     // 总体积（m³）
          totalWeight: ""      // 总重量（kg）
        },

        // 需求车辆表单数据
        vehicleRequirement: {
          orderId: "",
          vehicleType: "",
          vehicleLength: "",
          vehicleCount: "",
          createTime: ""
        },

        // 费用信息表单数据
        costInfo: {
          orderId: "",
          billingMethod: "",
          transportFee: "",
          insuranceFee: "",
          packagingFee: "",
          loadingUnloadingFee: "",
          transferFee: "",
          fuelFee: "",
          serviceFee: "",
          otherFee: "",
          totalCost: "",
          createTime: ""
        },

        // 付款方式
        paymentMethod: {
          orderId: "",
          cashPayment: "",
          prePayment: "",
          cashOnDelivery: "",
          periodicPayment: "",
          totalPayment: "",
          createTime: ""
        },
        // 订单备注
        orderRemark: {
          orderId: "",
          remark: "",
          createTime: ""
        },
      },

      // 货物表单数据
      goodsInfo: {
        goodsId: "",
        goodsName: "",
        quantity: "",
        unit: "",
        volume: "",
        weight: "",
        createTime: "",
        orderId: "",
      },

      // 货物列表数据
      goodsList: [],

      //顾客信息
      customerInfo: []
    };
  },

  computed: {

    // 计算总数量
    totalQuantity() {
      const total1= this.goodsList.reduce((total, item) => {
        return total + (parseFloat(item.quantity) || 0);
      }, 0);
      this.form.orderBasic.totalQuantity = total1;
      return total1;
    },

    // 计算总体积
    totalVolume() {
      const total = this.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.volume) || 0);
      }, 0);
      this.form.orderBasic.totalVolume = total.toFixed(2);
      return total.toFixed(2);
    },

    // 计算总重量
    totalWeight() {
      const total = this.goodsList.reduce((sum, item) => {
        return sum + (parseFloat(item.weight) || 0);
      }, 0);
      this.form.orderBasic.totalWeight = total.toFixed(2);
      return total.toFixed(2);
    }
  },

  methods: {
    // 添加货物
    addGoods() {
      this.open = true;
      this.title = "添加货物";
      // 重置货物表单
      this.goodsInfo = {
        orderId: this.form.orderBasic.orderId,
        goodsId: this.goodsList.length + 1,
        goodsName: "",
        quantity: "",
        unit: "",
        volume: "",
        weight: "",
        createTime: this.time,
      };
    },

    // 删除货物
    deleteGoods(index) {
      this.goodsList.splice(index, 1);
      // 重新设置序号
      this.goodsList.forEach((item, i) => {
        item.goodsId = i + 1;
      });
    },

    // 取消对话框
    cancelDialog() {
      this.open = false;
      if (this.$refs.goodsForm) {
        this.$refs.goodsForm.resetFields();
      }
    },

    // 重置整个表单
    resetForm() {
      //this.$message.info("已取消操作");
      // 清空表单数据
      this.form = {
        orderId: "",
        orderBasic: {
          customerName: "",
          customerCode: "",
          origin: "",
          destination: "",
          contract: "",
          transportType: "",
          goodsType: "",
          orderSource: "",
          orderTime: "",
          senderContact: "",
          senderPhone: "",
          senderAddress: "",
          planSendTime: "",
          receiverContact: "",
          receiverPhone: "",
          receiverAddress: "",
          planReceiveTime: "",
          totalQuantity: "",   // 总数量
          totalVolume: "",     // 总体积（m³）
          totalWeight: ""      // 总重量（kg）

        },
        vehicleRequirement: {
          orderId: "",
          type: "",
          vehicleLength: "",
          vehicleCount: "",
          createTime: ""
        },
        costInfo: {
          orderId: "",
          billingMethod: "",
          transportFee: "",
          insuranceFee: "",
          packagingFee: "",
          loadingUnloadingFee: "",
          transferFee: "",
          fuelFee: "",
          serviceFee: "",
          otherFee: "",
          totalCost: "",
          createTime: ""
        },
        paymentMethod: {
          orderId: "",
          cashPayment: "",
          prePayment: "",
          cashOnDelivery: "",
          periodicPayment: "",
          totalPayment: "",
          createTime: ""
        },
        // 订单备注
        orderRemark: {
          orderId: "",
          remark: "",
          createTime: ""
        }
      };
      this.goodsList = [];
    },

    // 保存订单
    save() {
      // 处理goodsList中createTime为空的情况，赋值为orderTime
      const processedGoodsList = this.goodsList.map(goods => {
        // 如果createTime未赋值或为空，则使用订单时间
        if (!goods.createTime && this.form.orderBasic.orderTime) {
          return {
            ...goods,
            createTime: this.form.orderBasic.orderTime
          };
        }
        return goods;
      });

      // 构建完整的订单数据
      const orderData = {
        ...this.form,
        goodsList: processedGoodsList
      };
      addOrder(orderData)
        .then(res => {
          this.$modal.msgSuccess("保存成功");
          this.resetForm();
          //或取新的订单编号
          requestOrderId().then(res => {
            const orderId = res.msg || "";
            this.form.orderBasic.orderId = orderId;
            // 给相关对象赋值orderId
            this.form.vehicleRequirement.orderId = orderId;
            this.form.costInfo.orderId = orderId;
            this.form.paymentMethod.orderId = orderId;
            this.form.orderRemark.orderId = orderId;
          })
            .catch(err => {
              this.$message.error("获取订单编号失败: " + (err.message || "未知错误"));
            });
        })
        .catch(err => {
          this.$message.error("保存失败: " + (err.message || "未知错误"));
        });
    },

    // 提交货物表单
    submitForm() {
      this.$refs.goodsForm.validate(valid => {
        if (valid) {
          this.goodsList.push({ ...this.goodsInfo });
          this.open = false;
          this.$message.success("添加成功");
        } else {
          return false;
        }
      });
    },

    // 计算付费合计
    sumTotalMoney() {
      this.form.paymentMethod.totalPayment = (
        (parseFloat(this.form.paymentMethod.cashPayment) || 0) +
        (parseFloat(this.form.paymentMethod.prePayment) || 0) +
        (parseFloat(this.form.paymentMethod.cashOnDelivery) || 0) +
        (parseFloat(this.form.paymentMethod.periodicPayment) || 0)
      ).toFixed(2);
    },

    // 计算服务费用合计
    sumTotalFee() {
      this.form.costInfo.totalCost = (
        (parseFloat(this.form.costInfo.transferFee) || 0) +
        (parseFloat(this.form.costInfo.insuranceFee) || 0) +
        (parseFloat(this.form.costInfo.packagingFee) || 0) +
        (parseFloat(this.form.costInfo.loadingUnloadingFee) || 0) +
        (parseFloat(this.form.costInfo.transportFee) || 0) +
        (parseFloat(this.form.costInfo.fuelFee) || 0) +
        (parseFloat(this.form.costInfo.serviceFee) || 0) +
        (parseFloat(this.form.costInfo.otherFee) || 0)
      ).toFixed(2);
    },

    // 处理下单时间变更
    handleOrderTimeChange(times) {
      if (times) {
        this.form.vehicleRequirement.createTime = times;
        this.form.costInfo.createTime = times;
        this.form.paymentMethod.createTime = times;
        this.form.orderRemark.createTime = times;
        this.time = times;

        // 如果已经有货物但没有创建时间，同步更新
        if (this.goodsList.length > 0) {
          this.goodsList = this.goodsList.map(goods => {
            if (!goods.createTime) {
              return { ...goods, createTime: times };
            }
            return goods;
          });
        }
      }
    },

    // 客户选择变化时触发：自动填充编码
    handleCustomerChange(selectedName) {
      // 情况1：如果未选择客户（清空选择）
      if (!selectedName) {
        this.form.orderBasic.customerCode = '';
        this.form.orderBasic.senderContact = '';
        this.form.orderBasic.senderPhone = '';
        return;
      }

      // 情况2：根据选中的客户名称，从客户列表中找到对应的编码
      const selectedCustomer = this.customerInfo.find(
        item => item.customerName === selectedName
      );

      // 填充客户编码
      if (selectedCustomer) {
        this.form.orderBasic.customerCode = selectedCustomer.customerNumber;
        this.form.orderBasic.senderContact = selectedCustomer.contactName;
        this.form.orderBasic.senderPhone = selectedCustomer.phoneNumber

        ;
      } else {
        this.form.orderBasic.customerCode = '';
        this.$message.warning('未找到对应的客户编码');
      }
    }

  },

  created() {
    // 系统生成订单编号
    requestOrderId()
      .then(res => {
        const orderId = res.msg || "";
        this.form.orderBasic.orderId = orderId;
        // 给相关对象赋值orderId
        this.form.vehicleRequirement.orderId = orderId;
        this.form.costInfo.orderId = orderId;
        this.form.paymentMethod.orderId = orderId;
        this.form.orderRemark.orderId = orderId;
      })
      .catch(err => {
        this.$message.error("获取订单编号失败: " + (err.message || "未知错误"));
      });

    //获取用户信息
    getCustomerInfo().then(res => {
      this.customerInfo = res.data || {};
      console.log(this.customerInfo);
    })
  }
};
</script>

<style scoped>
.order-basic-info {
  padding: 20px;
}

.send-section,
.receive-section {
  padding: 10px;
}

.send-section h4 {
  background-color: #ffebe6;
  padding: 5px;
  display: inline-block;
  margin-bottom: 10px;
}

.receive-section h4 {
  background-color: #e6ffed;
  padding: 5px;
  display: inline-block;
  margin-bottom: 10px;
}

.goods-info-card,
.vehicle-info-card,
.cost-info-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.goods-total {
  margin-top: 10px;
  text-align: right;
  font-weight: bold;
}

.payment-method {
  padding: 20px;
}

.button-group {
  text-align: right;
  margin-top: 20px;
}

.button-group .el-button {
  margin-left: 10px;
}
</style>
